package com.songlanyun.interceptor;

import com.alibaba.fastjson.JSON;
import com.songlanyun.common.annotation.AuthIgnore;
import com.songlanyun.common.config.resttplconfig.RegisterComponent;
import com.songlanyun.common.utils.R;
import com.songlanyun.common.utils.RedisKeys;
import com.songlanyun.modules.account.entity.AccountEntity;
import com.songlanyun.modules.account.service.AccountService;
import com.songlanyun.modules.shop.entity.ShopEntity;
import com.songlanyun.modules.shop.service.ShopService;
import com.songlanyun.modules.user.dao.SysUserDao;
import com.songlanyun.modules.user.entity.SysUserEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器  拦截小程序、App接口
 */
@Component
public class LoginApiInterceptor extends HandlerInterceptorAdapter {
    @Resource
    RedisTemplate<String, String> redisTemplate;

    @Resource
    private ShopService shopService;
    @Resource
    private AccountService accountService;

    @Autowired
    private RegisterComponent registerComponent;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        registerComponent.validateCode();
        String token = request.getHeader("token");//header方式

        String api_uid = redisTemplate.opsForValue().get(RedisKeys.getWxTokenConfigKey(token));

        //11/3 wc 修改  需要不拦截后台、小程序、app
//        if (!(StringUtils.isNotBlank(token)
//                || StringUtils.isNotBlank(api_uid))) {
//            response.setCharacterEncoding("UTF-8"); //设置编码格式
//            response.setContentType("application/json");
//            R responseBean = R.error(-400, "访问需要令牌");
//            response.getWriter().write(JSON.toJSONString(responseBean));
//            return false;
//        }

        request.setAttribute("api_uid", api_uid);

        //根据uid查询是否有店铺
        if (api_uid != null) {
            Long userId = Long.parseLong(api_uid);
            AccountEntity user = accountService.getUserById(userId, false);
            if(user!=null)
            {
                Long subjectionShopId = accountService.getUserById(userId,false).getSubjectionShopId();
                request.setAttribute("subjection_shop_id", subjectionShopId);//将shop_id存入request中
            }


        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }
}
